<template>
  <transition name="minimize"
    @before-enter="beforeEnter"
    @enter="enter"
    @after-enter="afterEnter"
    @before-leave="beforeLeave"
    @leave="leave"
    @after-leave="afterLeave">
    <div class="transition-wrapper" ref="transitionWrapper" v-show="isMinmize" @click="maximize">
      <div class="upload-file-wrapper" ref="uploadWin">
        <div class="upload-file_header">
          {{headText}}
          <div class="header-operate_wrapper">
            <div class="minimize" @click="minimize">-</div>
            <div class="close" @click="close">x</div>
          </div>
        </div>
        <div class="upload-file_content" :class="{'upload-file-progress_content': isShowUploadProgress}">
          <div class="upload_area" v-if="!isShowUploadProgress"  ref="dropContent">
            <div class="operate_wrapper">
              <div class="upload_btn" @click="uploadfile">上传文件</div>
              <div class="upload_tips">将文件拖拽至此区域</div>
            </div>
          </div>
          <div v-if="isShowUploadProgress" class="upload-preview_wrapper">
            <div class="upload-operate_wrapper">
              <div class="upload_btn" @click="uploadfile">上传文件</div>
              <div class="upload_tips">或者拖拽文件到下框</div>
            </div>
            <ul class="upload-progress_content">
              <li class="upload-progress-items" v-for="file in files">
                <div class="upload-thumbnail">
                  <img :src="file.imgUrlStr" width="100%" height="100%">
                </div>
                <div class="upload-file-info">
                  <div><span class="upload-file-name" :title="file.name">{{file.name}}</span><span class="upload-file-size">{{"("+file.size+")"}}</span></div>
                  <div class="progress-wrapper" v-if="!file.statusText">
                    <div class="progress" :style="{width: file.progressWidth}"></div>
                  </div>
                  <div class="upload-file-status_text" v-if="file.statusText">
                    {{file.statusText}}
                  </div>
                </div>
                <div class="upload-file-status_icon">
                  <span v-if="file.isImageFlag" class="previewBtn" @click="preview">预览</span>
                </div>
              </li>
            </ul>
          </div>
        </div>
        <div class="upload-file_footer" v-if="isShowUploadProgress">
          <div class="footer-operate_wrapper">
            <div class="upload_btn operate_ok" @click="ok">开始上传</div>
            <div class="upload_btn operate_cancel" @click="cancel">取消</div>
          </div>
        </div>
        <input type="file" ref="selectfile" name="files" hidden="true">
      </div>
      <v-preview :isshow="isshow" :slides="previewImg" v-if="previewImg.length" @closePreview="closePreview"></v-preview>
    </div>
  </transition>
</template>
<script>
  import preview from '../preview/preview';
  export default{
    data () {
      return {
        isShowUploadProgress: false,
        imgUrlStr: '',
        files: [],
        uploadfiles: [],
        previewImg: [],
        fileIcon: {
          doc: '../../../../static/imgs/fu_doc.gif',
          docx: '../../../../static/imgs/fu_doc.gif',
          pdf: '../../../../static/imgs/fu_pdf.gif',
          xls: '../../../../static/imgs/fu_exl.gif',
          xlsx: '../../../../static/imgs/fu_exl.gif'
        },
        isMinmize: true,
        curruploadstaus: 'max',
        isshow: false
      };
    },
    props: {
      headText: {
        type: String,
        default: '附件上传'
      }
    },
    methods: {
      uploadfile: function () {
        this.fireEvent(this.$refs.selectfile);
      },
      fireEvent: function (ele) {
        if (document.createEvent) {
          var evt = document.createEvent('MouseEvents');
          evt.initEvent('click', true, false);
          ele.dispatchEvent(evt);
        } else if (document.createEventObject) {
          ele.fireEvent('onclick');
        } else if (typeof ele.onclick === 'function') {
          ele.onclick();
        }
      },
      bytesToSize: function (bytes) {
        if (bytes === 0) {
          return '0 B';
        }
        var k = 1024;
        var sizes = ['B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB'];
        var i = Math.floor(Math.log(bytes) / Math.log(k));
        return (bytes / Math.pow(k, i)).toPrecision(3) + ' ' + sizes[i];
      },
      ok: function () {
        var self = this;
        var tempUpFiles = this.uploadfiles.concat();
        this.uploadfiles = [];
        for (var i = tempUpFiles.length - 1; i >= 0; i--) {
          (function (upfile) {
            self.$upload.uploadAction({
              url: 'http://localhost:3000/upload',
              file: upfile.file,
              success: function (result) {
                console.log(result);
                upfile.statusText = '完成';
                if (result && result.success && result.data) {
                }
              },
              progress: function (data) {
                if (data) {
                  upfile.progressWidth = 138 * (data.loaded / data.total) + 'px';
                }
              }
            });
          })(tempUpFiles[i]);
        }
      },
      cancel: function () {
        this.isShowUploadProgress = false;
        this.files = [];
        this.previewImg = [];
      },
      minimize: function () {
        console.log('minimize');
        this.isMinmize = false;
      },
      maximize: function () {
      },
      close: function () {
        console.log('close');
      },
      beforeEnter: function (el) {
        // 此时元素没有渲染到页面
      },
      enter: function (el) {
        // this.$refs.uploadWin.style.webkitTransform = 'translate3d(500px, -30px, 0)';
        // console.log(this.$refs.uploadWin.offsetHeight);// 强制触发重新渲染
        // this.$refs.uploadWin.style.webkitTransform = 'scale(1)';
      },
      afterEnter: function (el) {
        console.log('afterEnter', el);
        el.style.opacity = 'none';
      },
      beforeLeave: function (el) {
        console.log('beforeLeave', el);
      },
      leave: function (el) {
        this.$refs.transitionWrapper.style.webkitTransform = 'translate3d(500px, -30px, 0)';
        this.$refs.uploadWin.style.webkitTransform = 'scale(0.1)';
        console.log('leave', el);
      },
      afterLeave: function (el) {
        console.log('afterLeave', el);
        // this.$refs.transitionWrapper.style.display = 'block';
        this.isMinmize = true;
        console.log(this.$refs.uploadWin.offsetHeight);
      },
      readFile: function (files) {
        var reader = new FileReader();
        var self = this;
        if (!self.isShowUploadProgress) {
          self.isShowUploadProgress = true;
        }
        if (files.length > 0) {
          var file = files[0];
          // this.uploadfiles.push(file);
          // var isImageFlag =
          var fileName = file.name;
          var iconKey = fileName.substring(fileName.lastIndexOf('.') + 1, fileName.length);
          var fileObj = {};
          fileObj.name = file.name;
          fileObj.size = self.bytesToSize(file.size);
          fileObj.imgUrlStr = self.fileIcon[iconKey] || '';
          fileObj.progressWidth = '0px';
          fileObj.statusText = '';
          fileObj.file = file;
          fileObj.isImageFlag = /image\/\w+/.test(file.type);
          self.files.unshift(fileObj);
          self.uploadfiles.unshift(fileObj);
          // self.currentFiles = fileObj;
          reader.onloadend = function (e) {
            if (e.target.readyState === FileReader.DONE) {
              fileObj.imgUrlStr = this.result;
              self.previewImg.unshift({title: file.name, src: this.result});
              // if (isImageFlag) {
              //   fileObj.imgUrlStr = this.result;
              // }
              // fileObj.statusText = '完成';
            }
          };
          // reader.onprogress = function (e) {
          //   fileObj.progressWidth = 138 * (e.loaded / e.total) + 'px';
          // };
          if (fileObj.isImageFlag) {
            reader.readAsDataURL(file);
          }
          // else {
          //   reader.readAsBinaryString(file);
          // }
        }
      },
      preview: function () {
        this.isshow = true;
      },
      closePreview: function () {
        this.isshow = false;
      }
    },
    mounted: function () {
      var self = this;
      this.$refs.selectfile.onchange = function (event) {
        var fileList = event.target.files;
        self.readFile(fileList);
      };

      this.$refs.dropContent.addEventListener('drop', function (event) {
        // console.log(event);
        var fileList = event.dataTransfer.files;
        console.log(fileList);
        self.readFile(fileList);
        event.preventDefault();
      });

      // 阻止默认事件。比如说Chrome是直接将图片用浏览器打开
      this.$refs.dropContent.addEventListener('dragover', function (event) {
        event.preventDefault();
      });

      console.log(this.$upload);
    },
    components: {
      'v-preview': preview
    }
  };
</script>
<style scoped>
  .transition-wrapper{
    /*position: fixed;*/
    overflow: hidden;
    z-index: 10000;
  }
  .upload-file-wrapper{
    width: 400px;
    height: 420px;
    border-radius: 5px;
    border: 1px solid gray;
    transition: all .5s;
    transform-origin: center top;
  }

  .upload-file-wrapper>
  .upload-file_header{
    position: relative;
    box-sizing: border-box;
    height: 40px;
    line-height: 40px;
    padding-left: 5px;
    border-bottom: 1px solid lightgray;
    background-color: rgba(234,234,234,1);
  }

  .upload-file-wrapper>
  .upload-file_footer{
    position: relative;
    box-sizing: border-box;
    height: 40px;
    line-height: 40px;
    padding-left: 5px;
    border-top: 1px solid lightgray;
    background-color: rgba(234,234,234,1);
  }
  .footer-operate_wrapper{
    position: absolute;
    right: 5px;
  }

  .footer-operate_wrapper>
  div{
    display: inline-block;
  }

  .upload-file-wrapper>
  .upload-file_header>
  .header-operate_wrapper{
    position: absolute;
    width: 50px;
    height: 20px;
    line-height: 20px;
    right: 0;
    top: 50%;
    transform: translate3d(0, -50%, 0);
    user-select: none;
  }
  .upload-file-wrapper>
  .upload-file_header>
  .header-operate_wrapper>
  div{
    display: inline-block;
    width: 20px;
    height: 20px;
    text-align: center;
    cursor: pointer;
  }
  .upload-file-wrapper>
  .upload-file_header>
  .header-operate_wrapper>
  div:hover{
    background-color: rgba(204,204,204,1);
    color: white;
  }
  .upload-file-wrapper>
  .upload-file_content{
    /*position: relative;*/
    box-sizing: border-box;
    height: 380px;
    padding: 20px;
    background-color: white;
  }
  .upload-file-wrapper>
  .upload-file-progress_content{
    height: 340px;
  }
  .upload-file-wrapper>
  .upload-file_content>.upload_area{
    position: relative;
    width: 100%;
    height: 100%;
    border-radius: 5px;
    border: 1px solid lightgray;
    background-color: rgba(249,249,249,1);
  }
  .upload-file-wrapper>
  .upload-file_content>
  .upload_area>
  .operate_wrapper{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
  }
  .upload-file-wrapper .upload_btn{
    width: 150px;
    height: 30px;
    line-height: 30px;
    text-align: center;
    border-radius: 2px;
    border: 1px solid rgba(29,86,125, 1);
    box-shadow: 1px 1px 1px lightgray, -1px -1px 1px lightgray;
    cursor: pointer;
    user-select: none;
    background: linear-gradient(to bottom, #2993D5, #267EBA);
  }
  .upload_tips{
    padding: 15px;
    font-size: 12px;
    text-align: center;
  }
  .upload-file-wrapper .upload_btn:active{
    background: linear-gradient(to top, #2993D5, #267EBA);
  }

  .upload-preview_wrapper{
    height: 100%;
  }
  .upload-operate_wrapper{
    margin-bottom: 10px;
  }
  .upload-operate_wrapper>div{
    display: inline-block;
  }
  .upload-progress_content{
    position: relative;
    width: 100%;
    height: 250px;
    border-radius: 5px;
    border: 1px solid lightgray;
    background-color: rgba(249,249,249,1);
    overflow-y: auto;
  }
  .upload-progress_content>
  .upload-progress-items{
    display: flex;
    box-sizing: border-box;
    border-bottom: 1px solid lightgray;
    height: 55px;
  }
  .upload-thumbnail{
    box-sizing: border-box;
    flex-basis: 50px;
    padding: 9px;
  }

  .upload-file-info{
    flex: 1;
    padding-top: 8px;
  }
  .upload-file-name{
    display: inline-block;
    width: 160px;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;
    font-size: 15px;
  }
  .upload-file-size{
    margin-left: 5px;
    font-size: 15px;
    color: gray;
  }

  .upload-file-status_icon{
    position: relative;
    flex-basis: 50px;
  }

  .upload-file-status_icon>
  .previewBtn{
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate3d(-50%, -50%, 0);
    font-size: 12px;
    text-decoration: underline;
    cursor: pointer;
  }

  .progress-wrapper{
    box-sizing: border-box;
    width: 140px;
    height: 10px;
    margin-top: 10px;
    border-radius: 5px;
    border: 1px solid gray;
  }

  .progress-wrapper .progress{
    width: 30px;
    height: 8px;
    border-radius: 5px;
    background-color: rgba(48,132,210,1);
  }

  .footer-operate_wrapper>
  .operate_ok,
  .footer-operate_wrapper>
  .operate_cancel{
    width: 50px;
    height: 25px;
    font-size: 10px;
    line-height: 25px;
  }

  .footer-operate_wrapper>
  .operate_ok{
    width: 100px;
    color: white;
  }

  .footer-operate_wrapper>
  .operate_cancel{
    border: 1px solid rgba(136,136,136, 1);
    background: linear-gradient(to bottom, #FEFEFE, #F1F1F1);
  }

  .footer-operate_wrapper>
  .operate_cancel:active{
    background: linear-gradient(to bottom, #F1F1F1, #FEFEFE);
  }

  .upload-file-status_text{
    padding: 5px;
    font-size: 13px;
    color: green;
  }

/*  .lifade-enter{
    opacity: 0;
  }*/
  .minimize-enter-active, .minimize-leave-active{
    transition: all 0.5s;
  }
</style>
